package com.tsing.basic.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tsing.basic.entity.Role;
import com.tsing.basic.vo.req.BindPermissionReqVo;
import com.tsing.basic.vo.req.RolePageReqVo;
import com.tsing.basic.vo.resp.PermissionRespVo;
import com.tsing.basic.vo.resp.RoleRespVo;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * <p>
 * Mapper 接口
 * </p>
 *
 * @author TheTsing
 * @since 2021-03-29
 */
public interface RoleMapper extends BaseMapper<Role> {

    @Select("<script>" +
            "select 1 from t_user_role ur\n" +
            "inner join t_user u on ur.user_id=u.id\n" +
            "where ur.role_id in\n" +
            "<foreach collection='ids' item='item' open='(' close=')' separator=',' >\n" +
            "#{item}\n" +
            "</foreach>\n" +
            "limit 1" +
            "</script>")
    String haveRelevance(@Param("ids") List<String> ids);

    @Delete("<script>" +
            "delete from t_role_permission rp where rp.role_id in\n" +
            "<foreach collection='ids' item='item' open='(' close=')' separator=',' >\n" +
            "#{item}\n" +
            "</foreach>\n" +
            "</script>")
    void deleteRelevance(@Param("ids") List<String> ids);

    @Select("<script>" +
            "select r.id,r.name,r.description remark\n" +
            "from t_role r\n" +
            "<where>\n" +
            "<if test=\"reqVo.name!=null and reqVo.name!=''\">and r.name like concat('%',#{reqVo.name},'%')</if>\n" +
            "<if test=\"reqVo.remark!=null and reqVo.remark!=''\">and r.description like concat('%',#{reqVo.remark},'%')</if>\n" +
            "</where>\n" +
            "</script>")
    List<RoleRespVo> rolePage(RolePageReqVo reqVo, Page<Role> page);

    @Select("select p.id,p.url,p.description remark\n" +
            "from t_role_permission rp\n" +
            "inner join t_permission p on rp.permission_id=p.id\n" +
            "where rp.role_id=#{id}")
    List<PermissionRespVo> getPermissionByRoleId(@Param("id") String id);

    @Delete("delete from t_role_permission rp where rp.role_id=#{id}")
    void deletePermission(@Param("id") String id);

    @Insert("<script>" +
            "insert into t_role_permission(role_id,permission_id) values\n" +
            "<foreach collection='reqVo.permissionId' item='item' separator=',' >\n" +
            "( #{reqVo.id} , #{item} )\n" +
            "</foreach>\n" +
            "</script>")
    void bindPermission(@Param("reqVo") BindPermissionReqVo reqVo);

}
